package org.mcjug.oauth.gettokens;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

public class OauthActivity extends Activity {
	private CommonsHttpOAuthConsumer consumer;
	private CommonsHttpOAuthProvider provider;

	public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow";
	public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME
			+ "://callback";
	final String TAG = getClass().getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// you must have a file called secret.xml under /res/values with the key
		// and
		// secret for this to work
		String scope = "https://mail.google.com/";
		consumer = new CommonsHttpOAuthConsumer("anonymous", "anonymous");
		try {
			provider = new CommonsHttpOAuthProvider(
					"https://www.google.com/accounts/OAuthGetRequestToken?scope="
							+ URLEncoder.encode(scope, "utf-8"),
					"https://www.google.com/accounts/OAuthGetAccessToken",
					"https://www.google.com/accounts/OAuthAuthorizeToken?hd=default");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		new OAuthRequestTokenTask(this, consumer, provider).execute();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		final Uri uri = intent.getData();
		if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
			Log.i(TAG, "Callback received : " + uri);
			Log.i(TAG, "Retrieving Access Token");
			new RetrieveAccessTokenTask(this, consumer, provider, prefs)
					.execute(uri);
			finish();
		}
	}

}
